import { showErrorMsg } from '@/components/ErrorMsgModal/useErrorMsg';
import type { AxiosResponse, ApiResponse, ApiResponseError } from 'axios';
import { apiResponseIsError } from '../helper/response';
import { useAppNotificationStore } from '@/stores/feedback/useAppNotificationStore';
import { useLoginStore } from '@/stores/login';

// 接口返回的错误列表转换为antd表格数据
export function getAntDTableData(ext: { body: Array<string[]>; head: string[] }) {
  const { body, head } = ext;

  const columns = head.map((th, index) => ({
    dataIndex: index,
    title: th,
  }));
  return {
    columns,
    dataSource: body,
  };
}

function errorMsg(errRes: ApiResponseError) {
  if (typeof errRes === 'string') {
    errRes = { err: errRes, success: false, code: 999, msg: '请求发生错误' };
  }
  errRes.err = errRes.err || { err: '请求错误' };
  const {
    msg,
    code,
    err: { article_id: help_article_id, err, ext: extensions = { body: [], head: [] }, solution },
  } = errRes;
  /** 获取错误信息表格 */
  const antDTableData = getAntDTableData({
    body: extensions?.body || [],
    head: extensions?.head || [],
  });

  /** 表格错误消息，对于普通错误消息不响应 */
  return showErrorMsg({
    msg: msg || err || '',
    title: '操作失败',
    table: antDTableData,
    link: help_article_id
      ? {
          name: 'helpArticle',
          query: {
            id: help_article_id,
          },
        }
      : undefined,
    code: code,
    solution,
  });
}

/**
 * 处理响应错误的函数
 */
export function responseError(response: AxiosResponse<ApiResponse>) {
  if (apiResponseIsError(response.data)) {
    switch (response.data.code) {
      case 401:
      case 8000:
      case 8001:
      case 8002:
        useLoginStore().logout();
        break;
      default: {
        if (!response.config.option?.closeInterceptorNotify) {
          const length = response.data?.err?.ext?.body?.length ?? 0;
          // 有表格的提示
          if (length > 0) {
            errorMsg(response.data);
          } else {
            // 没有表格的普通提示
            const { code, msg, err } = response.data;

            const app = useAppNotificationStore();
            if (code === 405) {
              const values = Object.values(err as unknown as Record<any, string[]>).flat();

              app.notification?.error({
                message: '参数校验错误',
                description: () =>
                  h(
                    'div',
                    values.map(v => h('div', v)),
                  ),
                duration: 3,
              });
            } else if (code === 302) {
              app.notification?.error({
                message: '余额不足',
                description: '余额不足，请充值',
              });
            } else {
              app.notification?.error({
                message: '请求错误',
                description: msg,
              });
            }
          }
        }
        break;
      }
    }
  }
}
